package com.zjw.shortlink.project.mq.initialize;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.stream.StreamInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class ShortLinkStatsStreamInitializeTask {
    private final StringRedisTemplate stringRedisTemplate;

    @Value("${spring.data.redis.channel-topic.short-link-stats}")
    private String topic;
    @Value("${spring.data.redis.channel-topic.short_link:stats-stream:only-group}")
    private String group;
    @PostConstruct
    public void initializeConsumerGroup() {
        stringRedisTemplate.opsForStream().groups(topic)
                .stream()
                .map(StreamInfo.XInfoGroup::groupName)
                .filter(groupName -> groupName.equals(group))
                .findFirst()
                .ifPresentOrElse(group -> {}, () -> {
                    // 不存在消费者组，则创建
                    stringRedisTemplate.opsForStream().createGroup(topic, group);
                });
    }
}
